﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyAdmin.Web.Filters
{
    public class EasyActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 获取控制器、路由信息
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            // 获取控制器类型
            var controllerType = actionDescriptor!.ControllerTypeInfo;

            // 获取请求的方法
            var method = actionDescriptor!.MethodInfo;

            // 获取 HttpContext 和 HttpRequest 对象
            var httpContext = context.HttpContext;
            var httpRequest = httpContext.Request;
            //拦截白名单
            var whiteAction = new[] { "loginOut", "auth", "preview" };
            //只拦截post方法并且不是
            if (httpRequest.Method == "POST" && !whiteAction.Contains(actionDescriptor.ActionName))
            {
                // 是否匿名访问
                var allowAnonymous = context.Filters.Any(u => u is IAllowAnonymousFilter)
                    || controllerType.IsDefined(typeof(AllowAnonymousAttribute), true) || method.IsDefined(typeof(AllowAnonymousAttribute), true);
                if (!allowAnonymous)
                {
                    //如果不是匿名访问,抛出
                   // throw Oops.Bah("演示环境,禁止操作");
                }
            }
            await next();
        }
    }
}
